package com.yunban.project.api.text_check.service.impl;

import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.service.AiCorrectionService;
import com.yunban.project.api.text_check.utils.SSEHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: lijiajun
 * @date: 2025-03-10
 * @version: 1.0
 */
@Slf4j
@Service("hunYuanApplicationCorrectionService")
public class HunYuanApplicationCorrectionService implements AiCorrectionService {
    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        String botAppKey = config.getBotId();
        String url = config.getUrlPath();
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<String> resultHolder = new AtomicReference<>();
            SSEHandler.tencentSSEChat(url, text, botAppKey, taskId)
                    .subscribe(result -> {
                        resultHolder.set(result);
                        latch.countDown(); // 计数器减1，表示处理完成
                    }, error -> {
                        log.error("Error occurred: " + error.getMessage());
                        latch.countDown(); // 计数器减1，即使发生错误也要退出
                    });
            // 主线程等待异步处理完成
            latch.await();
            String result = resultHolder.get();
            if (!StringUtils.hasText(result)) {
                return null;
            }
            // 判断 result 中是否包含 “正确的表述应为：” 如果有，则取出 “正确的表述应为：”后的所有字符
            if (result.contains("正确的表述应为：")) {
                result = result.substring(result.indexOf("正确的表述应为：") + "正确的表述应为：".length());
                // 拼接统一响应String
                String resultFormat = "输出：%s错误等级：%s分类：固定用法来源：%s";
                return formatResponse(String.format(resultFormat, result, "一级", "/"), text);
            }
            // 如果纠错后的输出格式中，不包含“输出：”“分类：”“来源：” 那么则跳过
            if (!result.contains("输出：") && !result.contains("分类：") && !result.contains("来源：") && !result.contains("错误等级：")) {
                log.info("DeepSeek 纠正结果不包含\"输出：\"\"分类：\"\"错误等级：\"\"来源：\"，跳过本次纠正");
                return null;
            }
            // 返回结果
            return formatResponse(result, text);
        } catch (InterruptedException e) {
            log.error("【HunYuanApplicationCorrectionService.correction】Error occurred: " + e.getMessage());
            return null;
        }
    }

    public String correctionV2(String text, CorrectionConfig config) {
        String botAppKey = config.getBotId();
        String url = config.getUrlPath();
        try {
            CountDownLatch latch = new CountDownLatch(1);
            AtomicReference<String> resultHolder = new AtomicReference<>();
            SSEHandler.tencentSSEChat(url, text, botAppKey, "1")
                    .subscribe(result -> {
                        resultHolder.set(result);
                        latch.countDown(); // 计数器减1，表示处理完成
                    }, error -> {
                        log.error("Error occurred: " + error.getMessage());
                        latch.countDown(); // 计数器减1，即使发生错误也要退出
                    });
            // 主线程等待异步处理完成
            latch.await();
            String result = resultHolder.get();
            if (!StringUtils.hasText(result)) {
                return null;
            }
            // 判断 result 中是否包含 “正确的表述应为：” 如果有，则取出 “正确的表述应为：”后的所有字符
            if (result.contains("正确的表述应为：")) {
                result = result.substring(result.indexOf("正确的表述应为：") + "正确的表述应为：".length());
                // 拼接统一响应String
                String resultFormat = "输出：%s错误等级：%s分类：固定用法来源：%s";
                return formatResponse(String.format(resultFormat, result, "一级", "/"), text);
            }
            // 如果纠错后的输出格式中，不包含“输出：”“分类：”“来源：” 那么则跳过
            if (!result.contains("输出：") && !result.contains("分类：") && !result.contains("来源：") && !result.contains("错误等级：")) {
                log.info("DeepSeek 纠正结果不包含\"输出：\"\"分类：\"\"错误等级：\"\"来源：\"，跳过本次纠正");
//                return null;
            }
            return result;
            // 返回结果
//            return formatResponse(result, text);
        } catch (InterruptedException e) {
            log.error("【HunYuanApplicationCorrectionService.correction】Error occurred: " + e.getMessage());
            return null;
        }
    }
}
